Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

compare-func

Package Overview
Dependencies
Maintainers
1
Versions
12
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

compare-func

Get a compare function for array to sort

  • 2.0.0
  • latest
  • Source
  • npm
  • Socket score

Version published
Maintainers
1
Created

What is compare-func?

The compare-func npm package provides a simple way to create comparator functions for sorting arrays in JavaScript. It is particularly useful when you need to sort objects based on one or more of their properties. The package allows for easy creation of comparators using property names, custom getter functions, or multiple criteria.

What are compare-func's main functionalities?

Sorting by property name

This feature allows sorting an array of objects based on a specific property. In the provided code, an array of users is sorted by the 'age' property.

const compare = require('compare-func');
let users = [
  { name: 'Alice', age: 25 },
  { name: 'Bob', age: 20 },
  { name: 'Carol', age: 30 }
];
users.sort(compare('age'));
console.log(users);

Sorting by multiple criteria

This feature enables sorting based on multiple properties. The array of users is first sorted by 'name' and then by 'age' if the names are the same.

const compare = require('compare-func');
let users = [
  { name: 'Alice', age: 25 },
  { name: 'Bob', age: 20 },
  { name: 'Carol', age: 30 }
];
users.sort(compare(['name', 'age']));
console.log(users);

Sorting using a custom getter function

This feature allows for sorting using a custom function that defines the sorting criteria. Here, users are sorted based on the length of their names.

const compare = require('compare-func');
let users = [
  { name: 'Alice', age: 25 },
  { name: 'Bob', age: 20 },
  { name: 'Carol', age: 30 }
];
users.sort(compare(u => u.name.length));
console.log(users);

Other packages similar to compare-func

Keywords

FAQs

Package last updated on 15 May 2020

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc